package com.beilang.hotline.telrecord.page;

import com.beilang.base.util.Constant;
import com.beilang.base.util.DateUtil;
import com.beilang.base.util.ReportUtil;
import com.beilang.base.util.StringUtil;
import com.beilang.hotline.report.manager.ReportMgr;
import com.beilang.hotline.telattach.manager.TelattachMgr;
import com.beilang.hotline.telattach.model.TelattachModel;
import com.beilang.hotline.telrecord.manager.TelrecordMgr;
import com.beilang.hotline.telrecord.model.TelrecordModel;
import com.beilang.hotline.telrecord.to.SearchTO;
import com.beilang.hotline.user.model.UserModel;
import com.beilang.hotline.user.manager.UserMgr;
import com.beilang.hotline.knowledge.manager.KnowledgeMgr;
import com.beilang.hotline.template.manager.TemplateMgr;
import com.beilang.hotline.company.manager.CompanyMgr;
import org.springframework.context.ApplicationContext;
import static org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;

public class FileDownloadServlet extends HttpServlet {

    protected static final String DOWNLOAD_CONTENT_TYPE = "application/x-download";

    public FileDownloadServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

//    protected UserModel getLoginUser(HttpServletRequest request) {
//        return (UserModel) request.getSession().getAttribute("user");
//    }

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request  servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String attachId = request.getParameter("attachId");
        String recordId = request.getParameter("recordId");
        String genereateReport = request.getParameter("genereateReport");
        String genereateTelrptReport = request.getParameter("genereateTelrptReport");
        String genereatePersonrptReport = request.getParameter("genereatePersonrptReport");

        String genereateKnowlegeReport = request.getParameter("genereateKnowlegeReport");
        String genereateCompanyReport = request.getParameter("genereateCompanyReport");
        String genereateUserReport = request.getParameter("genereateUserReport");
        String genereateTemplateReport = request.getParameter("genereateTemplateReport");



        ReportUtil reportUtil = new ReportUtil();
        boolean isDownload = true;
        String downloadType = "";
        byte[] buf = new byte[0];
        String fileName = "";
        ServletContext context = this.getServletContext();
        ApplicationContext ctx = getRequiredWebApplicationContext(context);
        if (!StringUtil.isEmpty(attachId)) {
            TelattachMgr mgr = (TelattachMgr) ctx.getBean("telattachMgr");
            TelattachModel telattachModel = mgr.getTelattach(new Long(attachId));

            buf = telattachModel.getAttchContent();
            fileName = telattachModel.getAttchName();
        } else if (!StringUtil.isEmpty(recordId)) {
            TelrecordMgr mgr = (TelrecordMgr) ctx.getBean("telrecordMgr");
            TelrecordModel telrecordModel = mgr.getTelrecord(new Long(recordId));
            buf = reportUtil.readByteArrayOfSpecifiedFile(Constant.VOICE_FILEPATH + telrecordModel.getVoiceFileName());
            fileName = telrecordModel.getVoiceFileName();
        } else if ("Y".equalsIgnoreCase(genereateReport)) {
            String extFormat = request.getParameter("extFormat");
            String extDetail = request.getParameter("extDetail");
            String extMode = request.getParameter("extMode");
            String loginUserId = request.getParameter("loginUserId");
            SearchTO searchTO = genereateSearchTO(request);

            TelrecordMgr mgr = (TelrecordMgr) ctx.getBean("telrecordMgr");
            UserMgr userMgr = (UserMgr) ctx.getBean("userMgr");
            UserModel loginuserModel= userMgr.getUser(loginUserId);
            String name = mgr.genereateReport(loginuserModel, searchTO, extFormat, extDetail,extMode);
            buf = reportUtil.readByteArrayOfSpecifiedFile(Constant.FILEPATH + name);
            File file = new File(Constant.FILEPATH + name);
            fileName = name;
            isDownload = false;
//            if (name.toUpperCase().indexOf(".xls") != -1) {
//                downloadType = "application/vnd.ms-excel";
//            } else if (name.toUpperCase().indexOf(".pdf") != -1) {
//                downloadType = "application/pdf";
//            }
            downloadType = DOWNLOAD_CONTENT_TYPE;
            if (file.exists()) {
                file.delete();
            }
        } else if ("Y".equalsIgnoreCase(genereateTelrptReport)) {
            String dateFrom = request.getParameter("dateFrom");
            String dateTo = request.getParameter("dateTo");
            String workDays = request.getParameter("workDays");
            TelrecordMgr mgr = (TelrecordMgr) ctx.getBean("telrecordMgr");
            buf = mgr.genereatevoicefileReport(DateUtil.parseReportDt(dateFrom), DateUtil.parseReportDt(dateTo),new Integer(workDays).intValue());
            downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        } else if ("Y".equalsIgnoreCase(genereatePersonrptReport)) {
            com.beilang.hotline.person.to.SearchTO s = setSearchTO(request);

            ReportMgr mgr = (ReportMgr) ctx.getBean("reportMgr");
            buf = mgr.noTransactionGenerateContactReport(s);
            downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        }
        
        if ("Y".equalsIgnoreCase(genereateKnowlegeReport))
        {
            String sSysId = request.getParameter("sSysId");
            String sKnowledgeName = request.getParameter("sKnowledgeName");
            String sKnowledgeAnswer = request.getParameter("sKnowledgeAnswer");
            KnowledgeMgr mgr = (KnowledgeMgr) ctx.getBean("knowledgeMgr");
            com.beilang.hotline.knowledge.to.SearchTO s = new com.beilang.hotline.knowledge.to.SearchTO();
            if (!StringUtil.isEmpty(sSysId)) {
                s.setSysId(new Long(sSysId));
            }
            if (!StringUtil.isEmpty(sKnowledgeName)) {
                s.setKnowledgeName(sKnowledgeName);
            }
             if (!StringUtil.isEmpty(sKnowledgeAnswer)) {
                s.setKnowledgeAnswer(sKnowledgeAnswer);
            }
            buf=mgr.genereateKnowlegesReport(s);
                    downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        }else  if ("Y".equalsIgnoreCase(genereateCompanyReport))
        {
            String sCompanyName = request.getParameter("sCompanyName");
            String sCompanyNumber = request.getParameter("sCompanyNumber");
            CompanyMgr mgr = (CompanyMgr) ctx.getBean("companyMgr");
            com.beilang.hotline.company.to.SearchTO s = new com.beilang.hotline.company.to.SearchTO();
               if (!StringUtil.isEmpty(sCompanyName)) {
                s.setCompanyName(sCompanyName);
            }
              if (!StringUtil.isEmpty(sCompanyNumber)) {
                s.setCompanyNumber(sCompanyNumber);
            }
            buf=mgr.genereateCompanyReport(s);
                    downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        } else  if ("Y".equalsIgnoreCase(genereateUserReport))
        {
            String sUserId = request.getParameter("sUserId");
            String sUserName = request.getParameter("sUserName");
            String sUserRole = request.getParameter("sUserRole");
            String sDeptId = request.getParameter("sDeptId");
            UserMgr mgr = (UserMgr) ctx.getBean("userMgr");
            com.beilang.hotline.user.to.SearchTO s = new com.beilang.hotline.user.to.SearchTO();
            if (!StringUtil.isEmpty(sUserId)) {
                s.setUserId(sUserId);
            }
            if (!StringUtil.isEmpty(sUserName)) {
                s.setUserName(sUserName);
            }
            if (!StringUtil.isEmpty(sUserRole)) {
                s.setUserRole(sUserRole);
            }
            if (!StringUtil.isEmpty(sDeptId)) {
                s.setUserDeptId(sDeptId);
            }
            buf=mgr.genereateUserReport(s);
                    downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        }else  if ("Y".equalsIgnoreCase(genereateTemplateReport))
        {
            String sTemplateName = request.getParameter("sTemplateName");
            String sSysId = request.getParameter("sSysId");
            String sTitle = request.getParameter("sTitle");

            TemplateMgr mgr = (TemplateMgr) ctx.getBean("templateMgr");
            com.beilang.hotline.template.to.SearchTO s = new com.beilang.hotline.template.to.SearchTO();
            if (!StringUtil.isEmpty(sSysId)) {
                s.setSysId(new Long(sSysId));
            }
            if (!StringUtil.isEmpty(sTemplateName)) {
                s.setTemplateName(sTemplateName);
            }
            if (!StringUtil.isEmpty(sTitle)) {
                s.setTitle(sTitle);
            }

            buf=mgr.genereateTemplateReport(s);
                    downloadType = "application/vnd.ms-excel";
            fileName = reportUtil.getTempFileName(".xls");
        }

        response.reset();
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\""
                        + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        if (isDownload) {
            response.setContentType(DOWNLOAD_CONTENT_TYPE);
        } else {
            response.setContentType(downloadType);
        }

        response.setContentLength(buf.length);
        response.getOutputStream().write(buf, 0, buf.length);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    private com.beilang.hotline.person.to.SearchTO setSearchTO(HttpServletRequest request) {
        com.beilang.hotline.person.to.SearchTO s = new com.beilang.hotline.person.to.SearchTO();
        String sCustomArea = request.getParameter("sCustomArea");
        String sCompanyId = request.getParameter("sCompanyId");
        String personName = request.getParameter("personName");
        String sEmail = request.getParameter("sEmail");
        String sTelNo = request.getParameter("sTelNo");
        String sTelExt = request.getParameter("sTelExt");
        String sHandPhone = request.getParameter("sHandPhone");

        if (!StringUtil.isEmpty(sCustomArea)) {
            s.setCustomArea(sCustomArea);
        }
        if (!StringUtil.isEmpty(sCompanyId)) {
            s.setCompanyId(new Integer(sCompanyId));
        }
        if (!StringUtil.isEmpty(personName)) {
            s.setPersonName(personName);
        }
        if (!StringUtil.isEmpty(sEmail)) {
            s.setEmail(sEmail);
        }
        if (!StringUtil.isEmpty(sTelNo)) {
            s.setTelNo(sTelNo);
        }
        if (!StringUtil.isEmpty(sTelExt)) {
            s.setTelExt(sTelExt);
        }
        if (!StringUtil.isEmpty(sHandPhone)) {
            s.setHandPhone(sHandPhone);
        }

        String systemParamSize = request.getParameter("systemParamSize");

        if (!StringUtil.isEmpty(systemParamSize)) {
             List l = new ArrayList();
            for (int i = 0; i < Integer.valueOf(systemParamSize).intValue(); i++) {
                String value = request.getParameter("systemParam" + i);
                if (!StringUtil.isEmpty(value)) {
                    l.add(value);
                }
            }
            s.setAccessSystemList(l);
        }
        return s;
    }

    private SearchTO genereateSearchTO(HttpServletRequest request) throws IOException {
        SearchTO searchTO = new SearchTO();
        String recordId = request.getParameter("recordIdInd");
        if (!StringUtil.isEmpty(recordId) && "Y".equalsIgnoreCase(recordId)) {
            searchTO.setRecordIdSelected("Y");
        } else {
            searchTO.setRecordIdSelected("N");
        }
        String statusId = request.getParameter("statusId");
        if (!StringUtil.isEmpty(statusId) && "Y".equalsIgnoreCase(statusId)) {
            searchTO.setStatusIdSelected("Y");
        } else {
            searchTO.setStatusIdSelected("N");
        }
        String companyId = request.getParameter("companyId");
        if (!StringUtil.isEmpty(companyId) && "Y".equalsIgnoreCase(companyId)) {
            searchTO.setCompanyIdSelected("Y");
        } else {
            searchTO.setCompanyIdSelected("N");
        }
        String personId = request.getParameter("personId");
        if (!StringUtil.isEmpty(personId) && "Y".equalsIgnoreCase(personId)) {
            searchTO.setPersonIdSelected("Y");
        } else {
            searchTO.setPersonIdSelected("N");
        }
        String telId = request.getParameter("telId");
        if (!StringUtil.isEmpty(telId) && "Y".equalsIgnoreCase(telId)) {
            searchTO.setTelIdSelected("Y");
        } else {
            searchTO.setTelIdSelected("N");
        }
        String sysId = request.getParameter("sysId");
        if (!StringUtil.isEmpty(sysId) && "Y".equalsIgnoreCase(sysId)) {
            searchTO.setSysIdSelected("Y");
        } else {
            searchTO.setSysIdSelected("N");
        }
        String moduleId = request.getParameter("moduleId");
        if (!StringUtil.isEmpty(moduleId) && "Y".equalsIgnoreCase(moduleId)) {
            searchTO.setModuleIdSelected("Y");
        } else {
            searchTO.setModuleIdSelected("N");
        }
        String issueId = request.getParameter("issueId");
        if (!StringUtil.isEmpty(issueId) && "Y".equalsIgnoreCase(issueId)) {
            searchTO.setIssueIdSelected("Y");
        } else {
            searchTO.setIssueIdSelected("N");
        }
        String titleId = request.getParameter("titleId");
        if (!StringUtil.isEmpty(titleId) && "Y".equalsIgnoreCase(titleId)) {
            searchTO.setTitleIdSelected("Y");
        } else {
            searchTO.setTitleIdSelected("N");
        }
        String remarksId = request.getParameter("remarksId");
        if (!StringUtil.isEmpty(remarksId) && "Y".equalsIgnoreCase(remarksId)) {
            searchTO.setRemarksIdSelected("Y");
        } else {
            searchTO.setRemarksIdSelected("N");
        }
        String reasonId = request.getParameter("reasonId");
        if (!StringUtil.isEmpty(reasonId) && "Y".equalsIgnoreCase(reasonId)) {
            searchTO.setReasonIdSelected("Y");
        } else {
            searchTO.setReasonIdSelected("N");
        }
        String creatorId = request.getParameter("creatorId");
        if (!StringUtil.isEmpty(creatorId) && "Y".equalsIgnoreCase(creatorId)) {
            searchTO.setCreatorIdSelected("Y");
        } else {
            searchTO.setCreatorIdSelected("N");
        }

        String curOwnerId = request.getParameter("curOwnerId");
        if (!StringUtil.isEmpty(curOwnerId) && "Y".equalsIgnoreCase(curOwnerId)) {
            searchTO.setCurrentOwnerSelected("Y");
        } else {
            searchTO.setCurrentOwnerSelected("N");
        }

        String recordTime = request.getParameter("recordTime");
        if (!StringUtil.isEmpty(recordTime) && "Y".equalsIgnoreCase(recordTime)) {
            searchTO.setRecordTimeSelected("Y");
        } else {
            searchTO.setRecordTimeSelected("N");
        }
        String replyId = request.getParameter("replyId");
        if (!StringUtil.isEmpty(replyId) && "Y".equalsIgnoreCase(replyId)) {
            searchTO.setReplyIdSelected("Y");
        } else {
            searchTO.setReplyIdSelected("N");
        }

        String searchTORecordId = request.getParameter("searchTORecordId");
        String searchTOSystemId = request.getParameter("searchTOSystemId");
        String searchTOModuleId = request.getParameter("searchTOModuleId");
        String searchTOIssueId = request.getParameter("searchTOIssueId");
        String searchTOTitleRemarks = request.getParameter("searchTOTitleRemarks");
        String searchTOCurrentOwner = request.getParameter("searchTOCurrentOwner");
        String searchTOCreatorId = request.getParameter("searchTOCreatorId");
        String searchTORecordStatus = request.getParameter("searchTORecordStatus");
        String searchTORecordTimeStr = request.getParameter("searchTORecordTimeStr");
        String searchTORecordFromTimeStr = request.getParameter("searchTORecordFromTimeStr");
        String searchTORecordToTimeStr = request.getParameter("searchTORecordToTimeStr");
        String searchTOCompanyId = request.getParameter("searchTOCompanyId");
        String searchTOQuickSearchIndicator = request.getParameter("searchTOQuickSearchIndicator");
        if (!StringUtil.isEmpty(searchTORecordId)) {
            searchTO.setRecordId(new Long(searchTORecordId));
        }else
        {
           searchTO.setRecordId(new Long(0));
        }

        if (!StringUtil.isEmpty(searchTOSystemId)) {
            searchTO.setSystemId(new Long(searchTOSystemId));
        }else
        {
           searchTO.setSystemId(new Long(0));
        }
        if (!StringUtil.isEmpty(searchTOModuleId)) {
            searchTO.setModuleId(new Long(searchTOModuleId));
        }else
        {
           searchTO.setModuleId(new Long(0));
        }
        if (!StringUtil.isEmpty(searchTOIssueId)) {
            searchTO.setIssueId(new Long(searchTOIssueId));
        }else
        {
           searchTO.setIssueId(new Long(0));
        }
        if (!StringUtil.isEmpty(searchTOTitleRemarks)) {
            searchTO.setTitleRemarks(searchTOTitleRemarks);
        }else
        {
           searchTO.setTitleRemarks("");
        }
        
        if (!StringUtil.isEmpty(searchTOCurrentOwner)) {
            searchTO.setCurrentOwner(searchTOCurrentOwner);
        }
        if (!StringUtil.isEmpty(searchTOCreatorId)) {
            searchTO.setCreatorId(searchTOCreatorId);
        }

        if (!StringUtil.isEmpty(searchTORecordStatus)) {
            searchTO.setRecordStatus(searchTORecordStatus);
        }
        if (!StringUtil.isEmpty(searchTORecordTimeStr)) {
            Date dt = DateUtil.parseReportDt(searchTORecordTimeStr);
            searchTO.setRecordTime(dt);
            searchTO.setRecordTimeStr(DateUtil.formatDate(dt));
        }
        if (!StringUtil.isEmpty(searchTORecordFromTimeStr)) {
            Date dt = DateUtil.parseReportDt(searchTORecordFromTimeStr);
            searchTO.setRecordFromTime(dt);
            searchTO.setRecordFromTimeStr(DateUtil.formatDate(dt));
        }
        if (!StringUtil.isEmpty(searchTORecordToTimeStr)) {
            Date dt = DateUtil.parseReportDt(searchTORecordToTimeStr);
            searchTO.setRecordToTime(dt);
            searchTO.setRecordToTimeStr(DateUtil.formatDate(dt));
        }
        if (!StringUtil.isEmpty(searchTOCompanyId)) {
            searchTO.setCompanyId(new Long(searchTOCompanyId));
        }else
        {
           searchTO.setCompanyId(new Long(0)); 
        }
        if (!StringUtil.isEmpty(searchTOQuickSearchIndicator)) {
            searchTO.setQuickSearchIndicator(searchTOQuickSearchIndicator);
        }
        //System.out.println("searchTO="+searchTO);
        return searchTO;
    }
}
